package cn.regexp.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.regexp.domain.ShopGoods;
import cn.regexp.domain.ShopGoodsBook;
import cn.regexp.domain.ShopUser;
import cn.regexp.mapper.GoodsBookMapper;
import cn.regexp.service.IGoodsBookService;
import cn.regexp.service.IGoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class GoodsBookServiceImpl extends ServiceImpl<GoodsBookMapper, ShopGoodsBook> implements IGoodsBookService {
    @Autowired
    private IGoodsService goodsService;

    @Override
    public Boolean bookGoods(ShopGoodsBook shopGoodsBook, ShopUser shopUser) {
        ShopGoods shopGoods = goodsService.getById(shopGoodsBook.getGoodsId());
        // 不存在该商品，则返回 false
        if (ObjectUtil.isEmpty(shopGoods)) {
            return false;
        }
        // 查询数据库中当天某个商品是否存在已经预订的记录
        QueryWrapper<ShopGoodsBook> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", shopGoodsBook.getGoodsId())
                .eq("book_point", shopGoodsBook.getBookPoint())
                .apply("date_format (insert_time,'%Y-%m-%d') = date_format('" + DateUtil.date() + "','%Y-%m-%d')");
        List<ShopGoodsBook> shopGoodsBookList = super.list(wrapper);
        // 存在，则将数量 +1 并记录预订用户
        if (ObjectUtil.isNotEmpty(shopGoodsBookList)) {
            ShopGoodsBook goodsBook = shopGoodsBookList.get(0);
            goodsBook.setBookNum(goodsBook.getBookNum() + 1);
            goodsBook.setBookUserIds(goodsBook.getBookUserIds() + "," + shopUser.getId());
            goodsBook.setUpdateTime(new Date());
            return super.updateById(goodsBook);
        }
        // 不存在，则新增一条记录
        shopGoodsBook.setGoodsName(shopGoods.getGoodsName());
        shopGoodsBook.setWindowId(shopGoods.getWindowId());
        shopGoodsBook.setWindowName(shopGoods.getWindowName());
        shopGoodsBook.setBookUserIds(shopUser.getId().toString());
        shopGoodsBook.setBookNum(1);
        shopGoodsBook.setBookTime(DateUtil.date().offset(DateField.DAY_OF_YEAR, 1));
        shopGoodsBook.setInsertTime(new Date());
        shopGoodsBook.setUpdateTime(new Date());
        shopGoodsBook.setIsDel(ShopGoodsBook.DELETE_NO);
        return super.save(shopGoodsBook);
    }

}
